package com.monolithiot.sso.conf;

import com.monolithiot.sso.conf.prop.UploadFileConfigureProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.MultipartConfigElement;
import java.io.File;

/**
 * 2018/11/21 Create by 郭文梁
 * MultipartFileConfiguration
 * 表单文件上传配置
 *
 * @author 郭文梁
 * @date 2018/11/21
 */
@Configuration
public class MultipartFileConfiguration {
    private final UploadFileConfigureProperties uploadFileConfigureProperties;

    @Autowired
    public MultipartFileConfiguration(UploadFileConfigureProperties uploadFileConfigureProperties) {
        this.uploadFileConfigureProperties = uploadFileConfigureProperties;
    }


    /**
     * 配置文件上传相关内容
     *
     * @return MultipartConfigElement
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        File file = new File(uploadFileConfigureProperties.getBasePath(), uploadFileConfigureProperties.getTmp());
        if (!file.exists() || !file.isDirectory()) {
            if (!file.mkdirs()) {
                throw new RuntimeException("Could not create the upload tmp dir:" + file.getAbsolutePath());
            }
        }
        factory.setLocation(file.getAbsolutePath());
        return factory.createMultipartConfig();
    }
}
